import {
	getMenuByUsername
} from '../../../api/system.js';
const state = {
	//存放{ route: 路由路径, name: tab显示名称}对象数组
	maintabs: [{
		route: "/main/home",
		name: "首页",
		closable: false
	}],
	//当前被激活显示的那个Tab内容对应的route
	activeRoute: "/main/home",
	menuList: [{
			name: "非菜单路由",
			path: "",
			children: [{
				name: "个人中心",
				path: "/main/personal",
			}, {
				name: "借用历史",
				path: "/main/history",
			}, {
				name: "借用历史",
				path: "/main/adminlist",
			}]
		},

		{
			id: 4,
			name: "教室查看",
			path: "/main/queryclassroom",
			icon: "el-icon-search",
			children: []
		},
		{
			id: 8,
			name: "教室申请图表",
			path: "/main/charts",
			icon: "el-icon-picture-outline-round",
			children: []
		},

	],
	addTabName: ""
}

const mutations = {
	addTabMutation(state, route) {
		let isAlreadyIn = state.maintabs.some(item => item.route === route)
		this.commit("findMenuNameByRoute", route);
		state.activeRoute = route;
		if (!isAlreadyIn && state.addTabName !== "") {
			state.maintabs.push({
				route: route,
				name: state.addTabName
			});
		}
	},
	removeTab(state, route) {
		if (route !== "/main/home") {
			state.maintabs = state.maintabs.filter(
				item => item.route !== route
			)
			state.activeRoute = state.maintabs[state.maintabs.length - 1].route
		}
	},
	findMenuNameByRoute(state, route) {
		let findOne;
		for (let i in state.menuList) {
			let tmpArr = [];
			if (state.menuList[i].children.length == 0) {
				if (state.menuList[i].path === route) {
					tmpArr[0] = state.menuList[i];
				}
			} else {
				tmpArr = state.menuList[i].children.filter(
					item => item.path === route
				)
			}
			// let tmpArr = state.menuList[i].children.filter(
			// 	item => item.path === route
			// )
			if (tmpArr.length > 0) {
				findOne = tmpArr[0]
				break;
			}
		}
		state.addTabName = findOne ? findOne.name : "";
	}
}
const actions = {
	addTab({
		state,
		commit
	}, route) {
		//因为menuList里面有一项非菜单路由
		//大于等于一表示菜单已经加载过了，并且页面没刷新，
		//只是切换路由组件,不重新加载菜单
		// if (state.menuList.length <= 2) {
			
			
		// } else {
		// 	commit("addTabMutation", route); //菜单加载完成之后将Tab导航项添加
		// }
		getMenuByUsername().then(res => {
			state.menuList = [state.menuList[0], state.menuList[1], state.menuList[2], ...res.data1];
			commit("addTabMutation", route); //菜单加载完成之后将Tab导航项添加
		
		});
	}
}

export default {
	state,
	mutations,
	actions,
}
